#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/8/11 10:06
# @Name    : to_word_upload.py
# @email   : will05150707@163.com
# @Author  : wei.yan

import os
import traceback
from itertools import groupby

from pptx import Presentation
from docx import Document
from flask import request
import re
import logging

#
# def upload_file():
#     if request.method == "POST":
#         file = request.files["file"]
#         if file:
#             filename = file.filename
#             file.save(filename)  # 保存文件到当前目录
#
#             return f"文件 {filename} 上传成功！"

file_path_root = "H:\\"  # windows环境使用


# file_path_root = "/home/will"  # windows环境使用


# file_path_root = "/home/will" # linux环境使用

def to_word_upload_file():
    if request.method == "POST":
        file = request.files["file"]
        if file:
            filename = file.filename
            save_path = os.path.join(file_path_root, filename)
            file.save(save_path)
            return extract_ppt_titles(save_path)


def extract_ppt_titles(input_ppt):
    try:
        # 加载PPT文件
        prs = Presentation(input_ppt)

        # 创建Word文档
        doc = Document()
        try:
            # 遍历每一页PPT
            for slide in prs.slides:

                # 获取标题
                title_shape = slide.shapes.title
                if title_shape and title_shape.has_text_frame:
                    title = title_shape.text_frame.text
                else:
                    title = "未获取到标题"  # 如果标题为空，设置为"未获取到标题"
                doc.add_heading(removeNonAscii(title), level=1)  # 使用一级标题添加标题到Word文档

                # 获取正文
                text = []
                for shape in slide.shapes:
                    if shape.has_text_frame:
                        for paragraph in shape.text_frame.paragraphs:
                            text.append(removeNonAscii(paragraph.text))

                # 查找关键词
                keywords = re.findall(r'\w{4,}', ' '.join(text))
                # doc.add_paragraph(' '.join(keywords))  # 将关键词添加到Word文档
                doc.add_paragraph("正文关键词：" + ' '.join(text))  # 将关键词添加到Word文档

                # 获取备注
                notes_slide = slide.notes_slide
                notes_text = notes_slide.notes_text_frame.text
                if notes_text:
                    doc.add_paragraph("原备注：" + notes_text)
        except Exception as e:
            traceback_str = traceback.format_exc()
            print(traceback_str)

        # 构建输出文件路径
        # output_dir = os.path.dirname(input_ppt)  # 输入PPT的目录
        filename = os.path.splitext(os.path.basename(input_ppt))[0]
        # output_filename = os.path.join(output_dir, filename + ".docx")
        fileout = file_path_root + filename + ".docx"

        # 保存Word文档
        doc.save(fileout)

        return filename + ".docx"  # 返回输出文件路径

    except Exception as e:
        logging.exception(e)
        return "文件解析失败，请检查文件格式是否正确！"


def removeNonAscii(s):
    return re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]').sub(' ', s)
